package com.example.mykotlin.base.interceptor

import jakarta.servlet.Filter
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletRequest
import jakarta.servlet.ServletResponse
import jakarta.servlet.annotation.WebFilter
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

@WebFilter(urlPatterns = ["/**"])
@Component
class RequestLogFilter : Filter {
    companion object {
        val LOG: Logger = LoggerFactory.getLogger(RequestLogFilter::class.java)
    }

    override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain) {
        LOG.info("=== request start ===")
        servletRequest as HttpServletRequest
        servletResponse as HttpServletResponse

        LOG.info("request url: ${servletRequest.requestURL}")
        LOG.info("request method: ${servletRequest.method}")
        LOG.info(
            "request params: ${
                servletRequest.parameterMap.map { it.key to if (it.value.size == 1) it.value[0] else it.value }.toMap()
            }"
        )
        val jsonRequestWrapper = JsonRequestWrapper(servletRequest)
        LOG.info("request body: ${jsonRequestWrapper.getBodyString()}")
        val start = System.currentTimeMillis()
        filterChain.doFilter(jsonRequestWrapper, servletResponse)
        LOG.info("request time: ${System.currentTimeMillis() - start}ms")
        LOG.info("=== request end ===")
    }
}